package com.muchenx.db;

import com.muchenx.util.UIComponentUtil;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.lang3.StringUtils;

public final class DatasourceHelper {

    private final static String PREFIX = "jdbc:mysql://";
    private final static String SUFFIX = "?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true";

    public static void init(String ip, int port, String db, String username, String password) {
        String url = PREFIX + ip + ":" + port + "/" + db + SUFFIX;
        if (Holder.dataSource != null
                && StringUtils.equalsAnyIgnoreCase(url, Holder.dataSource.getJdbcUrl())
                && StringUtils.equalsAnyIgnoreCase(username, Holder.dataSource.getUsername())) {
            UIComponentUtil.errorAlert("数据库连接信息未发生变化，无需重复操作！");
            throw new RuntimeException("数据库连接信息未发生变化，无需重复操作！");
        }
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        config.setDriverClassName(com.mysql.cj.jdbc.Driver.class.getName());
        try {
            Holder.dataSource = new HikariDataSource(config);
        } catch (Exception e) {
            UIComponentUtil.errorAlert("初始化数据源异常：" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static HikariDataSource getDatasource() {
        if (Holder.dataSource == null) {
            init(DBCache.ip, DBCache.port, DBCache.db, DBCache.user, DBCache.pwd);
        }
        return Holder.dataSource;
    }

    private final static class Holder {
        private static volatile HikariDataSource dataSource;
    }
}
